package com.qing.microservices.esstarter.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author guoqf
 * @date 2022/5/16 17:43
 */
@Configuration
@EnableConfigurationProperties(ElasticSearchStarterConfigurationProperties.class)
public class ElasticSearchStarterAutoConfiguration implements DisposableBean {

    private TransportClient transportClient;

    @Resource
    private ElasticSearchStarterConfigurationProperties configurationProperties;

    @Override
    public void destroy() throws Exception {
        transportClient = new PreBuiltXPackTransportClient(settings());
    }

    private Settings settings() {
        return Settings.builder().put("cluster.name", configurationProperties.getClusterName())
                .put("xpack.security.user", configurationProperties.getUserName() + ":" + configurationProperties.getPassword())
                .build();
    }
}
